package gold.digger;

import gold.utils.InputUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC540 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int singleNonDuplicate(int[] nums) {
            return singleNonDuplicateBinarySearch(nums, 0, nums.length - 1);
        }

        public int singleNonDuplicateBinarySearch(int[] nums, int left, int right) {
            while (left <= right) {
                if (right - left == 0) return nums[left];
                if (right - left == 2) return nums[left] == nums[left + 1] ? nums[right] : nums[left];
                int mid = left + (right - left) / 2;

                if (nums[mid] != nums[mid - 1] && nums[mid] != nums[mid + 1]) return nums[mid];
                if (nums[mid] == nums[mid + 1]) {
                    if ((right - mid + 1) % 2 == 0) right = mid - 1;
                    else left = mid + 2;
                } else {
                    if ((mid - left + 1) % 2 == 0) left = mid + 1;
                    else right = mid - 2;
                }
            }

            return -1;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[1,1,2,3,3,4,4,8,8]");
        System.out.println(solution.singleNonDuplicate(arr));
    }

    public static void main(String[] args) throws Exception {
        LC540 an = new LC540();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
